//
//  SIngerViewController.m
//  DolphinMusic
//
//  Created by dllo on 15/3/25.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "SIngerViewController.h"
#import "ListDetailsTableViewCell.h"
#import "Song.h"
#import "AlbumCollectionViewCell.h"
#import "ListViewController.h"
#import "MusicPlayViewController.h"
#import "UIScrollView+MJRefresh.h"
#import "MJRefreshFooter.h"


@interface SIngerViewController () <UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain)UIButton *backButton;
@property (nonatomic, retain)UITableView *songTableView;
@property (nonatomic, retain)NSMutableArray *songArr;
@property (nonatomic, retain)UICollectionView *albumCollectionView;
@property (nonatomic, retain)NSMutableArray *albumArr;
@property (nonatomic, retain)UIScrollView *bgScrollView;

@property (nonatomic, retain)NSString *songNum;
@property (nonatomic, retain)NSString *albumNum;

@property (nonatomic, retain)MBProgressHUD *HUD;

@property (nonatomic, retain)NSString *nextPageSongAddress;
@property (nonatomic, retain)NSString *nextPageAlbumAddress;
@property (nonatomic, assign)NSInteger page;

@property (nonatomic, assign)NSInteger pageAlbum;

@end




@implementation SIngerViewController

- (void)dealloc
{
    [_nextPageSongAddress release];
    [_nextPageAlbumAddress release];
    [_albumNum release];
    [_songNum release];
    [_HUD release];
    [_bgScrollView release];
    [_albumArr release];
    [_albumCollectionView release];
    [_songArr release];
    [_songTableView release];
    [_backButton release];
    [_singer release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIWindow *window = [[[UIApplication sharedApplication] windows] firstObject];
    PlayView *playView = (PlayView*)[window viewWithTag:10001];
    playView.target = self.navigationController;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 20)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    [view1 release];
    
    
    
    CGFloat ab = 70.0 / 667;
    
    self.bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, VIEW_WIDTH, VIEW_HEIGHT - 20 - VIEW_HEIGHT * ab)];
    self.bgScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bgScrollView];
    self.bgScrollView.showsVerticalScrollIndicator = NO;
    self.bgScrollView.bounces = NO;
    [_bgScrollView release];
    
    self.HUD = [[MBProgressHUD alloc] initWithView:self.bgScrollView];
    [self.bgScrollView addSubview:self.HUD];
    self.HUD.labelText = @"Music is on the way...";
    self.HUD.dimBackground = YES;
    [self.HUD show:YES];
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.backButton.frame = CGRectMake(0, 20, 50, 44);
    
//    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    leftButton.frame = CGRectMake(0, 20, 50, 44);
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 12, 20, 20)];
    imageView.image = [UIImage imageNamed:@"backButton.png"];
    [self.backButton addSubview:imageView];
    [imageView release];
    
//    [self.backButton setBackgroundImage:[UIImage imageNamed:@"backButton.png"] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backButton];
    
    
    NSString *songStr = [NSString stringWithFormat:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.0.1&method=baidu.ting.artist.getSongList&format=json&order=2&tinguid=%@&artistid=%@&offset=0&limits=50", self.singer.ting_uid,self.singer.artist_id];
    

    
    NSString *albumStr = [NSString stringWithFormat:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.0.1&method=baidu.ting.artist.getAlbumList&format=json&order=1&tinguid=%@&offset=0&limits=30", self.singer.ting_uid];
    
    
    
    [NetHandler getDataWithUrl:albumStr completion:^(id dict) {
        [self setAlbumPageWithData:dict];
        self.albumNum = [dict objectForKey:@"albumnums"];
        
        [NetHandler getDataWithUrl:songStr completion:^(id dict1) {
            [self setSongPageWithData:dict1];
            
            [self.HUD hide:YES];
            
        }];
        
    }];
    
}

- (void)setSongPageWithData:(id)data
{
    self.songNum = [data objectForKey:@"songnums"];
    
    UIImageView *singerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 220)];
    [singerImageView setImageWithURL:[NSURL URLWithString:[self.singer.avatar_big stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    singerImageView.contentMode = UIViewContentModeScaleAspectFill;
    singerImageView.clipsToBounds = YES;
    [self.bgScrollView addSubview:singerImageView];
    [singerImageView release];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 170, VIEW_WIDTH, 30)];
    nameLabel.text = self.singer.name;
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.font = [UIFont systemFontOfSize:20];
    [self.bgScrollView addSubview:nameLabel];
    [nameLabel release];
    
    UILabel *areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 200, VIEW_WIDTH, 20)];
    areaLabel.text = [NSString stringWithFormat:@"%@歌手", self.singer.country];
    
    if (self.singer.country == nil) {
        areaLabel.text = nil;
    }
    
    areaLabel.font = [UIFont systemFontOfSize:16];
    areaLabel.textColor = [UIColor whiteColor];
    [self.bgScrollView addSubview:areaLabel];
    [areaLabel release];

    
    
    NSString *songNumStr = [NSString stringWithFormat:@"歌曲(%@)", self.songNum];
    NSString *albumNumStr = [NSString stringWithFormat:@"专辑(%@)", self.albumNum];
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:@[songNumStr, albumNumStr]];
    segment.frame = CGRectMake(0, 220, VIEW_WIDTH, 30);
    segment.tintColor = [UIColor lightGrayColor];
    [segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    segment.selectedSegmentIndex = 0;
    [self.bgScrollView addSubview:segment];
    [segment release];
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 250, VIEW_WIDTH, 50)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.bgScrollView addSubview:view1];
    [view1 release];
    
    UIButton *playAllButton = [UIButton buttonWithType:UIButtonTypeSystem];
    playAllButton.frame = CGRectMake(20, 10, 30, 30);
    [playAllButton setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    [view1 addSubview:playAllButton];
    
    UILabel *playAllLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 10, 100, 30)];
    playAllLabel.text = @"全部播放";
    playAllLabel.textColor = [UIColor grayColor];
    [view1 addSubview:playAllLabel];
    [playAllLabel release];
    
    UIView *view11 = [[UIView alloc] initWithFrame:CGRectMake(10, 299, VIEW_WIDTH - 20, 1)];
    view11.backgroundColor = [UIColor blackColor];
    view11.alpha = 0.1;
    [self.bgScrollView addSubview:view11];
    [view11 release];
    
    self.songArr = [NSMutableArray array];
    NSArray *arr = [data objectForKey:@"songlist"];
    
    if ([arr isKindOfClass:[NSArray class]]) {
    for (NSDictionary *dic in arr) {
        Song *song = [[Song alloc] initWithDictionary:dic];
        [self.songArr addObject:song];
        [song release];
    }
    }
    
    self.songTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 300, VIEW_WIDTH - 10, self.songArr.count * 60 + 60) style:UITableViewStylePlain];
    self.songTableView.dataSource = self;
    self.songTableView.delegate = self;
    self.songTableView.rowHeight = 60;
    self.songTableView.showsVerticalScrollIndicator = NO;
    [self.songTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(pullSongAction)];
    
    [self.songTableView registerClass:[ListDetailsTableViewCell class] forCellReuseIdentifier:@"singerSongReuse"];
    [self.bgScrollView addSubview:self.songTableView];
    [_songTableView release];
    
    
    self.songTableView.contentSize = CGSizeMake(0, self.songArr.count * 60);
    
    
    self.bgScrollView.contentSize = CGSizeMake(0, self.songTableView.frame.size.height + 300);
    
}

- (void)pullSongAction
{
    self.nextPageSongAddress = [NSString stringWithFormat:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.0.1&method=baidu.ting.artist.getSongList&format=json&order=2&tinguid=%@&artistid=%@&offset=%ld&limits=30", self.singer.ting_uid,self.singer.artist_id, self.page * 30 + 60];
    self.page++;
    [NetHandler getDataWithUrl:self.nextPageSongAddress completion:^(id dict) {
        NSArray *arr = [dict objectForKey:@"songlist"];
        
        if ([arr isKindOfClass:[NSArray class]]) {
            for (NSDictionary *dic in arr) {
                Song *song = [[Song alloc] initWithDictionary:dic];
                [self.songArr addObject:song];
                [song release];
            }
        [self.songTableView reloadData];
        [self.songTableView.footer endRefreshing];
        }
        else {
           self.songTableView.footer.state = MJRefreshFooterStateNoMoreData;
        }
        
        
    }];
    
    
    
}

- (void)segmentAction:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0) {
        [self.bgScrollView sendSubviewToBack:self.albumCollectionView];
        [self.bgScrollView bringSubviewToFront:self.songTableView];
        self.bgScrollView.contentSize = CGSizeMake(0, self.songTableView.frame.size.height + 300);
    }
    if (segment.selectedSegmentIndex == 1) {
        self.albumCollectionView.hidden = NO;
        [self.bgScrollView bringSubviewToFront:self.albumCollectionView];
        self.bgScrollView.contentSize = CGSizeMake(0, 260 + self.albumCollectionView.frame.size.height);
    }
}

- (void)setAlbumPageWithData:(id)data
{
    self.albumArr = [NSMutableArray array];
    
    NSArray *arr = [data objectForKey:@"albumlist"];
    if ([arr isKindOfClass:[NSArray class]]) {
    for (NSDictionary *dic in arr) {
        Album *album = [[Album alloc] initWithDictionary:dic];
        [self.albumArr addObject:album];
        [album release];
    }
    }
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(VIEW_WIDTH - 10, 80);
    flowLayout.minimumLineSpacing = 0;
    
    self.albumCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 260, VIEW_WIDTH - 10, self.albumArr.count * 80 + 80) collectionViewLayout:flowLayout];
    self.albumCollectionView.backgroundColor = [UIColor whiteColor];
    self.albumCollectionView.delegate = self;
    self.albumCollectionView.dataSource = self;
    self.albumCollectionView.hidden = YES;
    self.albumCollectionView.showsVerticalScrollIndicator = NO;
    [self.albumCollectionView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(albumCollectionPullAction)];
    [self.albumCollectionView registerClass:[AlbumCollectionViewCell class] forCellWithReuseIdentifier:@"albumCollectionResusefe"];
    [self.bgScrollView addSubview:self.albumCollectionView];
    [_albumCollectionView release];
    [flowLayout release];
    
}

- (void)albumCollectionPullAction
{
    self.nextPageAlbumAddress = [NSString stringWithFormat:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.0.1&method=baidu.ting.artist.getAlbumList&format=json&order=1&tinguid=%@&offset=%ld&limits=30", self.singer.ting_uid, self.pageAlbum * 60 + 30];
    
    self.pageAlbum++;
    
    [NetHandler getDataWithUrl:self.nextPageAlbumAddress completion:^(id dict) {
            NSArray *arr = [dict objectForKey:@"albumlist"];
        if ([arr isKindOfClass:[NSArray class]]) {
            for (NSDictionary *dic in arr) {
                Album *album = [[Album alloc] initWithDictionary:dic];
                [self.albumArr addObject:album];
                [album release];
            }
            [self.albumCollectionView reloadData];
            [self.albumCollectionView.footer endRefreshing];
        }
        else {
            self.albumCollectionView.footer.state = MJRefreshFooterStateNoMoreData;
        }
    }];
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.albumArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AlbumCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"albumCollectionResusefe" forIndexPath:indexPath];
    cell.album = [self.albumArr objectAtIndex:indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ListViewController *listVC = [[ListViewController alloc] init];
    Album *album = [self.albumArr objectAtIndex:indexPath.row];
    listVC.addressStr = [NSString stringWithFormat:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.0.1&method=baidu.ting.album.getAlbumInfo&format=json&album_id=%@",album.album_id];
    [self.navigationController pushViewController:listVC animated:YES];
    [listVC release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.songArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ListDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"singerSongReuse" forIndexPath:indexPath];
    cell.song = [self.songArr objectAtIndex:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MusicPlayViewController *musicVC = [MusicPlayViewController shareInstance];
    Song *song = [self.songArr objectAtIndex:indexPath.row];
    musicVC.playSongArr = [NSMutableArray array];
    for (Song *song1 in self.songArr) {
        NSString *songID = song1.song_id;
        [musicVC.playSongArr addObject:songID];
    }
    musicVC.playingNumber = indexPath.row;
    musicVC.songTitle = song.title;
    musicVC.singerName = song.author;
    musicVC.type = @"music";
    [musicVC setSongID:song.song_id];
    
}


- (void)backButtonAction:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIButton *button = (UIButton *)[window viewWithTag:1000];
    button.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
